﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Configuration;

namespace DVK.ConstantsGenerator
{
    public static class ContentTypesGenerator
    {
        public const string AttributeName = "Name";
        public const string AttributeID = "ID";

        public const string ElementContentType = "ContentType";

        public static void Generate()
        {
            string path = ConfigurationManager.AppSettings[Constants.ContentTypeConstantsOutput];

            FileStream file = File.Create(path, 1024, FileOptions.WriteThrough);
            StreamWriter writer = new StreamWriter(file);

            writer.WriteLine(GeneratorHelper.GetNamespaceString(Constants.Namespace));
            writer.WriteLine(GeneratorHelper.GetSummary("Generated class: " + GeneratorHelper.ParseName("ContentTypes")));
            writer.WriteLine(GeneratorHelper.GetClassString("ContentTypes"));

            foreach (var contentType in GetContentTypesXml().Elements(GeneratorHelper.GetName(ElementContentType)))
            {
                string id = contentType.Attribute(AttributeID).Value;
                //Parsing specific to DVK: 
                string name = contentType.Attribute(AttributeName).Value.Replace("$Resources:Dvk,", "").Replace(";", "").Replace("CT", "");

                char[] nameChars = name.ToCharArray();
                int upperCharLocation = 0;
                for (int i = nameChars.Length - 1; i >= 0; i--)
                {
                    if (char.IsUpper((nameChars[i])))
                    {
                        upperCharLocation = i;
                        break;
                    }
                }

                name = name.Remove(upperCharLocation);

                writer.WriteLine(
                        GeneratorHelper.GetClassString(/*ElementContentType + */GeneratorHelper.ParseName(name))
                    );

                writer.WriteLine(
                    GeneratorHelper.GetConstantFieldString(AttributeID, id)
                );

                //writer.WriteLine(
                //    GeneratorHelper.GetPropertyString(AttributeName, name)
                //);

                writer.WriteLine("\t" + GeneratorHelper.GetEndString());

            }

            writer.WriteLine(GeneratorHelper.GetEndString());
            writer.WriteLine(GeneratorHelper.GetEndString());
            writer.Flush();
            writer.Close();
        }


        public static XElement GetContentTypesXml()
        {
            XElement contentTypes = XElement.Load(
                    GeneratorHelper.GetPathFromAppSettings(Constants.ContentTypesFilePath)
                );

            return contentTypes;

        }


    }
}
